import { ElTable } from 'element-plus';
import {useTemplateRef} from 'vue'
const useTableScroll = (refName: any, tableData: Ref<any[]>) => {
    
    const tableEl:any = refName;
    console.log(tableEl.value);
    
    let tableBodyWrapper: HTMLElement | null, tableBody: HTMLElement | null;
    let timer: number | null = null;

    function initScroll() {
        nextTick(() => {
            
            if (tableEl.value) {
                tableBodyWrapper = tableEl.value.layout.table.refs.bodyWrapper;
                tableBody = tableBodyWrapper.firstElementChild?.firstElementChild as HTMLElement;
                tableEl.value.$el.addEventListener('mouseenter', stopScroll);
                tableEl.value.$el.addEventListener('mouseleave', startScroll);
                startScroll();
            } else {
                console.error(`未在el-table标签上声明ref="${refName}"`);
            }
        });
    }

    function startScroll() {
        setTimeout(() => {
            if (tableBody && tableBody.scrollHeight > tableBody.clientHeight) {
                let lastTime = performance.now();
                const animate = (currentTime: number) => {
                    if (currentTime - lastTime > 50) {
                        if (tableBody) {
                            tableBody.scrollTop += 1; // 增幅太小或变化太快可能会被浏览器自动优化为0
                            if (Math.ceil(tableBody.clientHeight + tableBody.scrollTop) >= tableBody.scrollHeight) {
                                tableBody.scrollTop = 0;
                            }
                        }
                        lastTime = currentTime;
                    }
                    timer = requestAnimationFrame(animate);
                };
                timer = requestAnimationFrame(animate);
            }
        }, 0);
    }

    function stopScroll() {
        if (timer) {
            cancelAnimationFrame(timer);
            timer = null;
        }
    }

    function resetScroll() {
        if (tableBody) {
            tableBody.scrollTop = 0;
        }
        stopScroll();
        startScroll();
    }

    function destroyScroll() {
        if (tableEl.value) {
            stopScroll();
            tableEl.value.$el.removeEventListener('mousemove', stopScroll);
            tableEl.value.$el.removeEventListener('mouseleave', startScroll);
        }
    }

    watch(
        () => tableData.value,
        () => {
            resetScroll();
        }
    );

    onMounted(() => {
        initScroll();
    });

    onBeforeUnmount(() => {
        destroyScroll();
    });

    return {
        initScroll,
        startScroll,
        stopScroll,
        resetScroll,
        destroyScroll
    };
};

export default useTableScroll;
